<template>
  <div class="newArea">
    <el-dialog
      v-model="initData.dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      title="城市选择"
      width="850px"
      @close="handlerClose"
    >
      <div class="content">
        <div class="content-select">
          <div>
            <span>城市过滤：</span>
            <el-input
              v-model="initData.filterText"
              class="content-select-input"
              placeholder="请输入城市名称"
              clearable
            ></el-input>
          </div>
          <el-button style="height: 40px" type="info" plain size="medium" @click="reset()">重置</el-button>
        </div>
        <el-tree
          ref="treeRef"
          :data="initData.treeData"
          :props="initData.defaultProps"
          :default-checked-keys="initData.defaultCheckedKeys"
          :default-expanded-keys="initData.defaultExpandedKeys"
          :filter-node-method="filterNode"
          show-checkbox
          node-key="Name"
          accordion
          @check="check"
        ></el-tree>
      </div>
      <div class="fooder">
        <el-button type="success" @click="confirm">确认</el-button>
        <el-button type="danger" @click="handlerClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { cityInfo } from '@/utils/newCityinfo.js'
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { ElTree } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'

// 返回数据结构及字段含义
// [
//   {
//     cityLength:8, //全部城市数量
//     isAllCity:true, //true:勾选全部城市，false:为勾选部分城市
//     provinceId:'6a02c31f-47e5-4e64-8213-1cf17d02f06f',
//     provinceName:'青海省',
//     cityList:[
//       {
//         ProvinceId: "6a02c31f-47e5-4e64-8213-1cf17d02f06f",
//         cityId: "2489823e-ccfa-4a0c-a375-96d48748149d",
//         cityName: "海北藏族自治州"
//       }
//     ],
//   }
// ]

const props = defineProps({
  // 默认勾选项，只需要传递城市ID, 如果传入的是省份ID会默认勾选下面所有市
  // defaultCheckedKeys: {
  //   type: Array,
  //   default: () => []
  // },
  //  是否勾选全国 true勾选全国
  isNationwide: {
    type: Boolean,
    default: false
  },
  // 是否单选 true单选，单选只针对处理市级选择，全国和省级无效,defaultCheckedKeys只取第一个数据作为默认项
  isSingle: {
    type: Boolean,
    default: false
  }
})

const initData = reactive({
  dialogVisible: false,
  treeData: [], // 树形图数据
  defaultProps: {
    children: 'Citys',
    label: 'Name'
  },
  filterText: '',
  checkAll: true, // 是否选中全国
  defaultExpandedKeys: [], // 默认展开项
  defaultCheckedKeys: [] // 默认勾选项，只需要传递城市ID, 如果传入的是省份ID会默认勾选下面所有市
})

watch(
  () => initData.filterText,
  (newData: string, predata: string) => {
    treeRef.value.filter(newData)
  }
)

const treeRef = ref<InstanceType<typeof ElTree>>()
const emits = defineEmits(['getCityData'])

onMounted(() => {
  const cityInfoArr = JSON.parse(JSON.stringify(cityInfo))
  cityInfoArr.unshift({
    Id: '10000',
    Name: '全国',
    Citys: []
  })
  cityInfoArr.map((item: { cityLength: any; Citys: string | any[]; disabled: boolean }) => {
    item.cityLength = item.Citys.length
    // 单选
    if (props.isSingle) {
      item.disabled = true
    }
  })
  initData.treeData = cityInfoArr
})

// 当复选框被点击的时候触发
const check = (data) => {
  if (data.Id === '10000') {
    if (initData.checkAll) {
      reset()
      treeRef.value.setCheckedKeys(['全国'])
      initData.checkAll = false
    } else {
      treeRef.value.setChecked('全国', false, true)
      initData.checkAll = true
    }
  } else {
    initData.checkAll = true
    treeRef.value.setChecked('全国', false, true)
    if (props.isSingle) {
      treeRef.value.setCheckedKeys([data.Name])
    }
  }
}

// 数据筛选
const filterNode = (value, data) => {
  if (!value) return true
  return data.Name.indexOf(value) !== -1
}

// 提交数据
const confirm = () => {
  const treeList = treeRef.value.getCheckedNodes(false, true)
  // 处理省级数据
  const provinceArr = []
  treeList.map((item) => {
    const provinceObj = {}
    // eslint-disable-next-line no-prototype-builtins
    if (item.hasOwnProperty('Citys')) {
      provinceObj.provinceName = item.Name
      provinceObj.provinceId = item.Id
      provinceObj.cityLength = item.cityLength || 0
      provinceArr.push(provinceObj)
    }
  })

  // 处理市级数据
  provinceArr.map((item) => {
    item.cityList = []
    treeList.map((it) => {
      // eslint-disable-next-line no-prototype-builtins
      if (!it.hasOwnProperty('Citys') && item.provinceId === it.ProvinceId) {
        const cityObj = {}
        cityObj.cityId = it.Id
        cityObj.ProvinceId = it.ProvinceId
        cityObj.cityName = it.Name
        item.cityList.push(cityObj)
      }
    })
  })
  provinceArr.map((item) => {
    if (item.cityLength === item.cityList.length) {
      item.isAllCity = true
    } else {
      item.isAllCity = false
    }
  })
  emits('getCityData', { cityData: provinceArr })
  reset()
  initData.dialogVisible = false
}

// 初始化打开弹窗
const init = (info) => {
  initData.dialogVisible = true
  initData.defaultExpandedKeys = []
  initData.defaultCheckedKeys = (info && info.defaultCheckedKeys) || []
  nextTick(() => {
    // 单选关闭所有展开项
    const treeAllNodes = treeRef.value.store._getAllNodes()
    if (treeAllNodes && treeAllNodes.length > 0) {
      treeAllNodes.map((item) => (item.expanded = false))
    }
    if (props.isSingle) {
      reset()
      // 单选关闭所有展开项
      // const treeAllNodes = this.$refs.tree.store._getAllNodes()
      // if (treeAllNodes && treeAllNodes.length > 0) {
      //   treeAllNodes.map(item => (item.expanded = false))
      // }
      if (initData.defaultCheckedKeys.length > 0) {
        treeRef.value.setCheckedKeys([initData.defaultCheckedKeys[0]])
        // 展开单个选择项
        initData.defaultExpandedKeys = [initData.defaultCheckedKeys[0]]
      }
    } else {
      if (initData.defaultCheckedKeys.length > 0) {
        // treeRef.value.setCheckedKeys([initData.defaultCheckedKeys[0]])
        // 展开单个选择项
        // initData.defaultExpandedKeys = [initData.defaultCheckedKeys[0]]
      } else {
        // 勾选全国
        if (initData.isNationwide) {
          reset()
          treeRef.value.setCheckedKeys(['全国'])
        }
      }
    }
  })
}

// 关闭弹窗
const handlerClose = () => {
  reset()
  initData.dialogVisible = false
}
// 重置数据
const reset = () => {
  treeRef.value && treeRef.value.setCheckedKeys([])
}

// 暴露给子组件的数据
defineExpose({
  init
})
</script>

<style lang="scss">
.newArea {
  .content {
    .el-tree {
      width: 800px;
      display: flex;
      flex-wrap: wrap;
      .el-tree-node {
        width: 200px;
      }
    }
  }
  .content-select {
    border-bottom: 1px solid rgb(228, 227, 223);
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    .content-select-input {
      width: 200px;
      margin-bottom: 10px;
      margin-left: 20px;
    }
  }
  .fooder {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
